package com.stooges.adjustment.controller;

import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.annotation.Resource;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import com.github.pagehelper.PageInfo;
import com.stooges.adjustment.form.AccountForm;
import com.stooges.adjustment.form.ApplyAlterForm;
import com.stooges.adjustment.form.ApplyConditionForm;
import com.stooges.adjustment.service.CommonService;
import com.stooges.adjustment.service.TeacherService;
import com.stooges.adjustment.util.Constants;
import com.stooges.adjustment.util.ExcelUtil;
import com.stooges.adjustment.util.SimpleValidator;
import com.stooges.adjustment.view.ApplyView;
import com.stooges.adjustment.view.MajorCollectionView;
import com.stooges.adjustment.view.OauthView;
import com.stooges.adjustment.view.ResultView;

/**
 * 教师处理器
 * @author 张超
 *
 */
@RequestMapping("/teacher")
@Controller
public class TeacherController {
	private static final Logger log = LoggerFactory.getLogger(TeacherController.class);
	@Resource
	private TeacherService teacherService;
	@Resource
	private CommonService commonService;
	/**
	 * 打开教师主页
	 * @return
	 */
	@RequestMapping("/home")
	public String home(){
		return "teacher/home";
	}
	/**
	 * 打开开账户页面
	 * @return
	 */
	@RequestMapping("/toopenaccount")
	public String toOpenAccount(HttpSession session){
		OauthView oauthView = (OauthView)session.getAttribute(Constants.SESSION_USER);
		//检查是否有开账户权限，没有就返回没有权限页面
		if(oauthView.getRole().getId()==3){
			return "teacher/open-account";
		}else{
			return "error/noauth";
		}
	}
	/**
	 * 查询报考情况
	 * @param session
	 * @param modelMap
	 * @return
	 */
	@RequestMapping("/applycount")
	public String applyCount(HttpSession session,ModelMap modelMap){
		//查询所在学院及相关专业
		OauthView oauthView = (OauthView)session.getAttribute(Constants.SESSION_USER);
		MajorCollectionView majorCollection = teacherService.findMajorCollectByOauthId(oauthView.getId());
		modelMap.put("majorCollection", majorCollection);
		return "teacher/apply-count";
	}
	/**
	 * 开账户
	 * @param accountForm 账户表单
	 * @param session
	 * @return
	 */
	@RequestMapping(value="/openaccount",method = RequestMethod.POST)
	@ResponseBody
	public ResultView openAccount(@RequestBody AccountForm accountForm,HttpSession session){
		OauthView sesOauth = (OauthView) session.getAttribute(Constants.SESSION_USER);
		ResultView resultView = new ResultView();
		if(sesOauth.getRole().getId()!=Constants.ROLE_TEACHER1){
			resultView.setStatus(ResultView.ERROR);
			resultView.setMsg("非常抱歉，您没有开账户的权限！");
			return resultView;
		}
		//检查表单是否是否正确
		Map<String,String> errorMap = new HashMap<String,String>();
		if(validateAccountForm(accountForm,errorMap)){
			trimAccountForm(accountForm);
			//添加账户
			try {
				boolean addResult = teacherService.addAccount(accountForm,sesOauth.getId());
				if(addResult){
					resultView.setStatus(ResultView.SUCCESS);
				}else{
					resultView.setStatus(ResultView.ERROR);
					resultView.setMsg("账户添加失败，请稍候重试！");
				}
			} catch (Exception e) {
				resultView.setStatus(ResultView.ERROR);
				resultView.setMsg("账户添加失败，请稍候重试！");
				log.error(e.getMessage(),e);
			}
		}else{
			resultView.setValue(ResultView.ERROR);
			resultView.setMsg(errorMap.get("error"));
		}
		
		return resultView;
	}
	/**
	 * 修改报考状态
	 * @param applyAlterForm 修改申请状态表单
	 * @param session
	 * @return
	 */
	@RequestMapping(value="/updapplystatus",method = RequestMethod.POST)
	@ResponseBody
	public ResultView updateApplyStatus(@RequestBody ApplyAlterForm applyAlterForm,HttpSession session){
		ResultView resultView = new ResultView();
		OauthView sesOauth = (OauthView) session.getAttribute(Constants.SESSION_USER);
		try {
			if(applyAlterForm!=null){
				applyAlterForm.setOperatorId(sesOauth.getId());
			}
			boolean updateResult = teacherService.updateApplyStatus(applyAlterForm);
			if(updateResult){
				resultView.setStatus(ResultView.SUCCESS);
			}else{
				resultView.setStatus(ResultView.ERROR);
				resultView.setMsg("参数有误或该同学已被其他专业录取！");
			}
		} catch (Exception e) {
			log.error(e.getMessage(),e);
			resultView.setStatus(ResultView.ERROR);
			resultView.setMsg("参数有误，请稍候重试！");
		}
		return resultView;
	}
	/**
	 * 根据条件显示申请记录
	 * @param applyConditionForm
	 * @param session
	 * @return
	 */
	@RequestMapping(value="/showapplylist",method = RequestMethod.POST)
	@ResponseBody
	public ResultView showApplyList(@RequestBody ApplyConditionForm applyConditionForm,HttpSession session){
		ResultView resultView = new ResultView();
		if(applyConditionForm==null){
			resultView.setStatus(ResultView.ERROR);
		}else{
			OauthView sesOauth = (OauthView) session.getAttribute(Constants.SESSION_USER);
			Integer collegeId = commonService.findCollegeIdByOauthId(sesOauth.getRole().getId(),sesOauth.getId());
			applyConditionForm.setCollegeId(collegeId);
			//根据条件查询申请记录
			PageInfo<ApplyView> applyList = teacherService.findAllApply(applyConditionForm);
			resultView.setStatus(ResultView.SUCCESS);
			resultView.setValue(applyList);
		}
		return resultView;
	}
	/**
	 * 显示学生申请详情
	 * @param studentId 学生ID
	 * @param session
	 * @return
	 */
	@RequestMapping(value="/showapplierdetail",method = RequestMethod.POST)
	@ResponseBody
	public ResultView showApplierDetail(@RequestBody Long studentId,HttpSession session){
		OauthView oauthView = (OauthView) session.getAttribute(Constants.SESSION_USER);
		ResultView resultView = new ResultView();
		resultView.setStatus(ResultView.SUCCESS);
		resultView.setValue(teacherService.findApplierDetail(studentId,oauthView.getId(),oauthView.getRole().getId()));
		return resultView;
	}
	/**
	 * 根据条件下载申请记录
	 * @param applyConditionForm
	 * @param session
	 * @return
	 */
	@RequestMapping(value="/downloadapplys",method = RequestMethod.POST)
	public String downloadApplys(ApplyConditionForm applyConditionForm,HttpSession session,HttpServletResponse response){
		if(applyConditionForm==null){
			applyConditionForm = new ApplyConditionForm();
		}
		OauthView sesOauth = (OauthView) session.getAttribute(Constants.SESSION_USER);
		Integer collegeId = commonService.findCollegeIdByOauthId(sesOauth.getRole().getId(), sesOauth.getId());
		applyConditionForm.setCollegeId(collegeId);
		// 根据条件查询申请记录
		List<ApplyView> applyList = teacherService.findExcelApplys(applyConditionForm);
		
		
		String fileName = "excel文件";
		List<Map<String, Object>> list = createExcelRecord(applyList);
		String columnNames[] = { "姓名","报考学院", "报考专业",  "总分", "本科学校", "本科专业" };// 列名
		String keys[] = { "name", "collegeName", "majorName", "totalScore", "undergraduateSchool", "undergraduateMajor" };// map中的key
		ByteArrayOutputStream os = new ByteArrayOutputStream();
		try {
			ExcelUtil.createWorkBook(list, keys, columnNames).write(os);
		} catch (IOException e) {
			e.printStackTrace();
		}
		byte[] content = os.toByteArray();
		InputStream is = new ByteArrayInputStream(content);
		// 设置response参数，可以打开下载页面
		response.reset();
		BufferedInputStream bis = null;
		BufferedOutputStream bos = null;
		try {
			response.setContentType("application/vnd.ms-excel;charset=utf-8");
			response.setHeader("Content-Disposition", "attachment;filename=" + new String((fileName + ".xls").getBytes(), "iso-8859-1"));
			ServletOutputStream out = response.getOutputStream();
			bis = new BufferedInputStream(is);
			bos = new BufferedOutputStream(out);
			byte[] buff = new byte[2048];
			int bytesRead;
			while (-1 != (bytesRead = bis.read(buff, 0, buff.length))) {
				bos.write(buff, 0, bytesRead);
			}
		}catch (final Exception e) {
			log.error(e.getMessage(),e);
		} finally {
			try {
				if (bis != null)
					bis.close();
				if (bos != null)
					bos.close();
			} catch (IOException e) {
				log.error(e.getMessage(),e);
			}
		}
		return null;
	}
	/**
	 * 检查帐号表单
	 * @param accountForm 帐号
	 * @param errorMap 错误信息
	 * @return 帐号输入是否正确
	 */
	private boolean validateAccountForm(AccountForm accountForm,Map<String,String> errorMap){
		//检查非空
		if(accountForm==null){
			errorMap.put("error","请输入用户名及密码");
			return false;
		}else if(SimpleValidator.isBlank(accountForm.getUsername())){
			errorMap.put("error","请输入用户名");
			return false;
		}else if(SimpleValidator.isBlank(accountForm.getPassword())){
			errorMap.put("error","请输入密码");
			return false;

		//检查格式
		}else if(accountForm.getPassword().trim().length()<6||accountForm.getPassword().trim().length()>15){
			errorMap.put("error","请输入6-15位数字、字母、特殊字符组成的密码");
			return false;
		}

		//检查用户名重复性
		String checkUsername = accountForm.getUsername();
		if(Character.isDigit(accountForm.getUsername().charAt(0))){
			checkUsername = "T"+checkUsername;
		}
		return !teacherService.validateAccountDuplicate(checkUsername,errorMap);
	}
	/**
	 * 删除账号表单的空白
	 * @param accountForm 新开账户
	 * @return 开立账户
	 */
	private AccountForm trimAccountForm(AccountForm accountForm){
		accountForm.setUsername(accountForm.getUsername().trim());
		accountForm.setPassword(accountForm.getPassword().trim());
		if(SimpleValidator.isNotBlank(accountForm.getName())){
			accountForm.setName(accountForm.getName().trim());
		}
		return accountForm;
	}
	/**
	 * 生成excel记录
	 * @param applys 申请记录
	 * @return
	 */
	private List<Map<String, Object>> createExcelRecord(List<ApplyView> applys) {
		List<Map<String, Object>> listmap = new ArrayList<Map<String, Object>>();
		Map<String, Object> map = new HashMap<String, Object>();
		map.put("sheetName", "学生报考情况统计");
		listmap.add(map);
		for (ApplyView apply : applys) {
			Map<String, Object> mapValue = new HashMap<String, Object>();
			mapValue.put("name", apply.getName());
			mapValue.put("collegeName", apply.getCollegeName());
			mapValue.put("majorName", apply.getMajorName());
			mapValue.put("totalScore", apply.getTotalScore());
			mapValue.put("undergraduateSchool", apply.getUndergraduateSchool());
			mapValue.put("undergraduateMajor", apply.getUndergraduateMajor());
			listmap.add(mapValue);
		}
		return listmap;
	}
}
